<template>
  <div class="account-box">
    <!-- 登录方式切换 -->
    <div class="toggle">
      <a @click="isMsgLogin=false" v-if="isMsgLogin" href="javascript:;">
        <i class="iconfont icon-user"></i> 使用账号登录
      </a>
      <a @click="isMsgLogin=true" v-else href="javascript:;">
        <i class="iconfont icon-msg"></i> 使用短信登录
      </a>
    </div>

    <Form class="form" ref="target" :validation-schema="schema" v-slot="{errors}">
      <!-- 使用账号登录 -->
      <template v-if="!isMsgLogin">
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <Field v-model="formData.account" name="account" :class="{error:errors.account}"
              type="text" placeholder="请输入用户名" />
          </div>
          <div class="error" v-if="errors.account"><i
              class="iconfont icon-warning" />{{errors.account}}</div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-lock"></i>
            <Field v-model="formData.password" name="password" type="password"
              placeholder="请输入密码" />
          </div>
          <div class="error" v-if="errors.password"><i
              class="iconfont icon-warning" />{{errors.password}}</div>
        </div>
      </template>

      <!-- 使用验证码登录 -->
      <template v-else>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <Field v-model="formData.mobile" name="mobile" type="text" placeholder="请输入手机号"
              :class="{error:errors.mobile}" />
          </div>
          <div class="error" v-if="errors.mobile"><i
              class="iconfont icon-warning" />{{errors.mobile}}</div>
        </div>
        <div class=" form-item">
          <div class="input">
            <i class="iconfont icon-code"></i>
            <Field v-model="formData.code" name="code" type="password" placeholder="请输入验证码"
              :class="{error:errors.code}" />
            <span @click="send" class="code"> {{time===0?'发送验证码':`${time}秒后发送`}}</span>
            <!-- <div>{{time===0?'发送验证码':`${time}秒后发送`}}</div> -->
          </div>
          <div class="error" v-if="errors.code"><i class="iconfont icon-warning" />{{errors.code}}
          </div>
        </div>
      </template>

      <div class="form-item">
        <div class="agree">
          <Field as="XtxCheckbox" name="isAgree" v-model="formData.isAgree" />
          <span>我已同意</span>
          <a href="javascript:;">《隐私条款》</a>
          <span>和</span>
          <a href="javascript:;">《服务条款》</a>
        </div>
        <div class="error" v-if="errors.isAgree"><i
            class="iconfont icon-warning" />{{errors.isAgree}}</div>
      </div>
      <a @click="login" href="javascript:;" class="btn">登录</a>
      <!-- <span id="qqLoginBtn"></span> -->
    </Form>
    <div class="action">
      <!-- qq登录 -->
      <a
        href="https://graph.qq.com/oauth2.0/authorize?client_id=100556005&amp;response_type=token&amp;scope=all&amp;redirect_uri=http%3A%2F%2Fwww.corho.com%3A8080%2F%23%2Flogin%2Fcallback">
        <img src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png"
          alt="QQ登录"></a>

      <div class="url">
        <a href="javascript:;">忘记密码</a>
        <a href="javascript:;">免费注册</a>
      </div>
    </div>
  </div>
</template>
<script>
import Message from '@/components/Message'
import { useStore } from 'vuex'
import { ref, reactive } from 'vue'
import { Form, Field } from 'vee-validate'
import { account, isAgree, mobile, code, password } from '@/utils/validate'
import { userMobileLoginMsg } from '@/api/user'
import { useCountdown } from '@/compositions/index'
import { useRouter, useRoute } from 'vue-router'
// import QC from 'qc'
// import QC from 'qc'
export default {
  name: 'LoginForm',
  components: { Form, Field },
  setup () {
    // onMounted(() => {
    //   // 组件渲染完毕，使用QC生成QQ登录按钮
    //   QC.Login({
    //     btnId: 'qqLoginBtn'
    //   })
    // })
    // 是否短信登录
    const isMsgLogin = ref(false)
    // 表单数据 与接口文档中的字段一致
    const formData = reactive({
      account: 'xiaotuxian001',
      password: '123456',
      mobile: '13241051259',
      isAgree: true,
      code: '123456'
    })
    const schema = {
      account: account,
      isAgree: isAgree,
      mobile: mobile,
      code: code,
      password: password
    }
    const target = ref(null)
    // 点击发送验证码按钮
    const send = async () => {
      // 通过校验才能发送ajax
      if (mobile(formData.mobile) !== true) {
        Message({ type: 'error', text: '手机号码格式不对' })
        return
      }
      if (time.value !== 0) {
        return
      }
      // 发送ajax
      try {
        await userMobileLoginMsg(formData.mobile)
        Message({ type: 'success', text: '验证码已发送,注意查收' })
        start(60)
      } catch (err) {
        // console.dir(err)
        Message({ type: 'error', text: err.response.data.message })
      }
    }
    // 点击登录
    const login = () => {
      // 手动兜底校验
      target.value.validate().then(res => {
        // console.log('手动兜底校验', res)
        if (!res) { return }

        isMsgLogin.value ? doUserMobileLogin() : doUserAccountLogin()
      })
      // 发ajax
    }
    const store = useStore()
    const router = useRouter()
    const route = useRoute()
    // 账号登录
    const doUserAccountLogin = async () => {
      // 调用action
      const user = {
        account: formData.account,
        password: formData.password
      }
      try {
        // 需要在vuex的action主动抛出错误
        await store.dispatch('user/userAccountLogin', user)
        // 合并购物车
        await store.dispatch('cart/mergeLocalCart')
        // 登录提示
        Message({ type: 'success', text: '登录成功' })
        // 路由跳转到指定页面或主页
        router.push(route.query.return_url || '/')
      } catch (err) {
        // console.dir('错误对象')
        // console.dir(err)
        Message({ type: 'error', text: err.message })
      }
    }
    // 手机号登录
    const doUserMobileLogin = async () => {
      console.log('store.....', store)
      // 调用action
      const user = {
        mobile: formData.mobile,
        code: formData.code
      }
      try {
        // 需要在vuex的action主动抛出错误
        await store.dispatch('user/userMobileLogin', user)
        // 同步购物车
        await store.dispatch('cart/mergeLocalCart')
        Message({ type: 'success', text: '登录成功' })
        // 进入主页
        router.push('/')
      } catch (err) {
        console.dir('错误对象')
        // console.dir(err)
        Message({ type: 'error', text: err.message })
      }
    }
    const { time, start } = useCountdown()

    return { isMsgLogin, formData, login, schema, target, send, time, start }
  }
}
</script>
<style lang="less" scoped>
// 账号容器
.account-box {
  .toggle {
    padding: 15px 40px;
    text-align: right;
    a {
      color: @xtxColor;
      i {
        font-size: 14px;
      }
    }
  }
  .form {
    padding: 0 40px;
    &-item {
      margin-bottom: 28px;
      .input {
        position: relative;
        height: 36px;
        > i {
          width: 34px;
          height: 34px;
          background: #cfcdcd;
          color: #fff;
          position: absolute;
          left: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 18px;
        }
        input {
          padding-left: 44px;
          border: 1px solid #cfcdcd;
          height: 36px;
          line-height: 36px;
          width: 100%;
          &.error {
            border-color: @priceColor;
          }
          &.active,
          &:focus {
            border-color: @xtxColor;
          }
        }
        .code {
          position: absolute;
          right: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 14px;
          background: #f5f5f5;
          color: #666;
          width: 90px;
          height: 34px;
          cursor: pointer;
        }
      }
      > .error {
        position: absolute;
        font-size: 12px;
        line-height: 28px;
        color: @priceColor;
        i {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }
    .agree {
      a {
        color: #069;
      }
    }
    .btn {
      display: block;
      width: 100%;
      height: 40px;
      color: #fff;
      text-align: center;
      line-height: 40px;
      background: @xtxColor;
      &.disabled {
        background: #cfcdcd;
      }
    }
  }
  .action {
    padding: 20px 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .url {
      a {
        color: #999;
        margin-left: 10px;
      }
    }
  }
}
</style>
